<template>
  <div class="chart-k">
    <div :id="chartId" ref="chartkline" class="flow-line" style="width: 100%; height: 100%;"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import { initKOption2 } from '@/utils/k-line.js'
import { initKOption } from '@/utils/k-line2.js'
export default {
  props: {
    flow: {
      type: Object,
      default: () => ({})
    },
	kType:{
		type:Number,
		default:1
	},
	nowprice:{
		type:Number,
		default:0
	}
  },
  data() {
    return {
      chartId: `chart-${Math.random().toString(36).substr(2, 9)}`, // 生成唯一ID
	  ispinch:false
    };
  },
  mounted() {
    this.initChart();
  },
  watch: {
    flow: {
      handler: 'updateChart',
      deep: true
    },
	kType:{
		handler: 'initChart',
		deep: true
	},
	// nowprice:{
	// 	handler: 'initChart',
	// 	deep: true
	// }
  },
  methods: {
    initChart() {
		if (this.echartInstance) {
		  this.echartInstance.dispose();
		}
      if (this.flow) {
		  // #ifdef H5
		  const chartContainer = document.getElementById(this.chartId);
		  // #endif
		  // #ifdef APP
		  const chartContainer = this.$refs.chartkline
		  // #endif
        if (chartContainer) {
          this.echartInstance = echarts.init(chartContainer);
		  this.updateChart();
        }
      }
    },
	calculateMA(dayCount, data) {
	  var result = [];
	  for (var i = 0, len = data.length; i < len; i++) {
	    if (i < dayCount) {
	      result.push('-');
	      continue;
	    }
	    var sum = 0;
	    for (var j = 0; j < dayCount; j++) {
	      sum += +data[i - j][1];
	    }
	    result.push(sum / dayCount);
	  }
	  return result;
	},
    updateChart() {
		if (!this.echartInstance || !this.flow) return;
		// [时间，开盘价，收盘，最低，最高，持仓量，成交量]]
		if(this.kType ==1){
			// this.echartInstance.setOption(option,true);
			// this.echartInstance.setOption(initKOption(this.flow,this.nowprice),true);
			this.echartInstance.setOption(initKOption(this.flow),true);
			this.setupDragging(this.$refs.chartkline);
			this.onTouch();
		}else{
			this.echartInstance.setOption(initKOption2(this.flow),true);
		}
    },
	setupDragging(chartContainer) {
	      // 监听 touchstart 和 touchmove 事件来实现拖动
	      const zr = this.echartInstance.getZr();
	      zr.on('mousedown', (event) => {
			  // console.log('mousedown事件 zr.on.mousedown,',event.event.changedTouches[0].clientX);
	        this.isDragging = true; // 开始拖动
	        this.lastX = event.event.changedTouches[0].clientX; // 记录初始的 X 位置
	      });
	
	      zr.on('mousemove', (event) => {
			  // console.log('mousemove事件 zr.on.mousemove,',event);
	        if (this.isDragging && !this.ispinch) {
	          const currentX = event.event.changedTouches[0].clientX;
	          const deltaX = currentX - this.lastX; // 计算 X 移动的距离
	          this.lastX = currentX; // 更新上次的位置
	
	          // 更新 dataZoom 的 start 和 end，控制平移
	          const moveStep = (deltaX / chartContainer.clientWidth) * 100; // 按图表宽度的百分比计算平移量
			  // console.log("moveStep",moveStep);
	          let dataZoom = this.echartInstance.getOption().dataZoom[0];
			  // console.log("dataZoom",dataZoom);
	          let newStart = Math.max(0, dataZoom.start - moveStep);
	          let newEnd = Math.min(100, dataZoom.end - moveStep);
				// console.log("newStart",newEnd);
				// console.log("newEnd",newEnd);
				if(newEnd>=100){
					newEnd = 100
					newStart = 80
				}
				if(newStart<=0){
					newEnd = 20
					newStart = 0
				}
	          this.echartInstance.dispatchAction({
	            type: 'dataZoom',
	            dataZoomIndex: 0,
	            start: newStart,
	            end: newEnd,
				zoomLock:false,
	          });
	        }
	      });
	      zr.on('mouseup', (event) => {
			  // console.log('mouseup事件 zr.on.mouseup,',event);
	        this.isDragging = false;
	      });
	},
	onTouch() {
		  const chartElement = document.getElementById(this.chartId);
		  const hammer = new Hammer(chartElement);
		
		  // 启用缩放手势
		  hammer.get("pinch").set({ enable: true });
		
		  // 启用滑动手势
		  hammer.get("swipe").set({ direction: Hammer.DIRECTION_VERTICAL });
		
		  // 设置 touch-action，允许垂直滑动
		  chartElement.style.touchAction = 'pan-y';
		
		  // 监听缩放事件
		  hammer.on("pinch", (event) => {
		      const scale = event.scale; // 获取缩放比例
				this.ispinch = true
		      // 正常缩放行为，scale > 1 表示放大，scale < 1 表示缩小
		      let newScale = 100 / scale; // 根据缩放比例调整范围
		      
		      // 根据缩放比例调整 dataZoom 的范围
		      const start = Math.max(0, 100 - newScale); // 计算起始位置
		      const end = Math.min(100, newScale); // 计算结束位置
		  
		      // 更新 echarts 的 dataZoom 范围
		      this.echartInstance.dispatchAction({
		        type: "dataZoom",
		        dataZoomIndex: 0, // 指定 dataZoom 组件的索引
		        start, // 设置 dataZoom 的起始位置
		        end,   // 设置 dataZoom 的结束位置
				zoomLock: true,
		      });
		  });
		 // 监听缩放结束的事件 (pinchend)
		  hammer.on('pinchend', (event) => {
		    console.log('缩放已停止');
			this.ispinch = false
		    // 在缩放停止时执行的逻辑
		  });
		 // hammer.on('pan', (event) => {
			//  console.log('hammer.js 平移:', event);
		 //     const deltaX = event.deltaX;
		 //     console.log('平移距离:', deltaX);
		 //   });
		  // 监听 swipe 事件
		  hammer.on("swipe", (event) => {
		    if (event.direction === Hammer.DIRECTION_UP) {
		      // 向上滑动时减少 scrollTop 值
		      const currentScrollTop = document.documentElement.scrollTop || window.scrollY;
		      const newScrollTop = Math.max(currentScrollTop - 100, 0); // 减少 100 像素，并防止值为负
		      window.scrollTo({
		        top: newScrollTop,
		        behavior: 'smooth' // 平滑滚动
		      });
		      console.log('Swipe up detected, scrollTop:', newScrollTop);
		    } else if (event.direction === Hammer.DIRECTION_DOWN) {
		      // 向下滑动逻辑 (可根据需要调整)
		      const currentScrollTop = document.documentElement.scrollTop || window.scrollY;
		      const newScrollTop = currentScrollTop + 100; // 增加 100 像素
		      window.scrollTo({
		        top: newScrollTop,
		        behavior: 'smooth' // 平滑滚动
		      });
		      console.log('Swipe down detected, scrollTop:', newScrollTop);
		    }
		  });
		}
  },
  beforeUnmount() {
    if (this.echartInstance) {
      this.echartInstance.dispose();
    }
  }
};
</script>

<style lang="scss" scoped>
.chart-k {
  width: 100%;
  height: 800rpx;
  
  .flow-line {
    width: 100%;
    height: 100%;
    touch-action: pan-y; // 允许垂直滚动
  }
}

</style>
